//
//  CollectViewController.m
//  myCar
//
//  Created by 王子洁 on 14/11/5.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "CollectViewController.h"
#import "DataBaseHandler.h"
#import "SaveNews.h"
#import "UIImageView+WebCache.h"
#import "WebViewController.h"
#import "WebColor.h"
#import "CollectTableViewCell.h"
#import "WebController.h"
#import "HttpViewController.h"
#import "ForumDetailController.h"
@interface CollectViewController ()<UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate, UIScrollViewDelegate,UIGestureRecognizerDelegate>

@property (nonatomic, retain)NSMutableArray *arr;
@property (nonatomic, retain)NSMutableArray *forumArr;
@property (nonatomic, retain)NSMutableArray *TZArr;
@property (nonatomic, retain)NSMutableArray *carArr;

@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)UITableView *forumTableView;
@property (nonatomic, retain)UITableView *TZTableView;
@property (nonatomic, retain)UITableView *CarTableView;

@property (nonatomic, retain)SaveNews *news;
@property (nonatomic, retain)DataBaseHandler *handler;
@property (nonatomic, retain) NSMutableArray *collectionArr;

@property (nonatomic, retain)UISegmentedControl *segment;
@property (nonatomic, retain)UIScrollView *scrollView;

@end

@implementation CollectViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.arr = [NSMutableArray array];
        self.news = [[SaveNews alloc] init];
        self.forumArr = [NSMutableArray array];
        self.TZArr = [NSMutableArray array];
        self.carArr = [NSMutableArray array];
        self.collectionArr = [NSMutableArray array];
    }
    return self;
}

- (void)dealloc
{
    [_arr release];
    [_news release];
    [_forumArr release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [self initTableView];
    [self setHandler];
}

- (void)setHandler
{
    self.handler = [DataBaseHandler shareInstance];
    [self.handler openDB];
    [self.handler createTable];
    [self.handler createForumTable];
    
}

- (void)initTableView
{
    self.segment = [[UISegmentedControl alloc] initWithItems:@[@"文章", @"论坛", @"帖子", @"找车"]];
    self.segment.frame = CGRectMake(0, 0, self.view.frame.size.width, 30);
    self.segment.selectedSegmentIndex = 0;
    [self.segment addTarget:self action:@selector(pageChange:) forControlEvents:UIControlEventValueChanged];
    [self.segment setBackgroundImage:[UIImage imageNamed:@"segment0.jpg"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    
    [self.segment setBackgroundImage:[UIImage imageNamed:@"segment.jpg"] forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
    
    [self.segment setDividerImage:[UIImage imageNamed:@"segment1.jpg"] forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    NSDictionary *colorAttr = [NSDictionary dictionaryWithObject:[UIColor grayColor] forKey:UITextAttributeTextColor];
    
    [self.segment setTitleTextAttributes:colorAttr forState:UIControlStateNormal];
    
    NSDictionary *colorAttr1 = [NSDictionary dictionaryWithObject:[WebColor dodgerBlue] forKey:UITextAttributeTextColor];
    
    [self.segment setTitleTextAttributes:colorAttr1 forState:UIControlStateSelected];
    
    [self.view addSubview:self.segment];
    [_segment release];
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 30, self.view.bounds.size.width, self.view.bounds.size.height - 30)];
    self.scrollView.delegate = self;
    self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width * 4, 0);
    self.scrollView.pagingEnabled = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.bounces = NO;
    //self.scrollView.scrollEnabled = NO;
    [self.view addSubview:self.scrollView];
    [_scrollView release];
    
    // 收藏的文章列表
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 30 - 49) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    // tableView不显示分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [WebColor whiteSmoke];
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    [self.scrollView addSubview:self.tableView];
    [_tableView release];
    
    self.forumTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 30 - 49) style:UITableViewStylePlain];
    self.forumTableView.dataSource = self;
    self.forumTableView.delegate = self;
    self.forumTableView.backgroundColor = [WebColor whiteSmoke];
    // tableView不显示分割线
    self.forumTableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self.scrollView addSubview:self.forumTableView];
    [_forumTableView release];
    
    self.TZTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 2, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 30 - 49) style:UITableViewStylePlain];
    self.TZTableView.dataSource = self;
    self.TZTableView.delegate = self;
    self.TZTableView.backgroundColor = [WebColor whiteSmoke];
    // tableView不显示分割线
    self.TZTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self.scrollView addSubview:self.TZTableView];
    [_TZTableView release];
    
    self.CarTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 3, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 30 - 49) style:UITableViewStylePlain];
    self.CarTableView.dataSource = self;
    self.CarTableView.delegate = self;
    self.CarTableView.backgroundColor = [WebColor whiteSmoke];
    // tableView不显示分割线
    self.CarTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self.scrollView addSubview:self.CarTableView];
    [_CarTableView release];
    
    
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    return NO;
}

- (void)pageChange:(UISegmentedControl *)segment
{
    self.scrollView.contentOffset = CGPointMake(self.view.bounds.size.width * segment.selectedSegmentIndex, 0);
    
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView

{
    CGFloat offsetX = self.scrollView.contentOffset.x;
    
    CGFloat width = self.view.bounds.size.width;
    
    self.segment.selectedSegmentIndex  = offsetX / width;
    if (self.segment.selectedSegmentIndex == 2) {
        [self.TZTableView reloadData];
    } else if (self.segment.selectedSegmentIndex == 3) {
        [self.CarTableView reloadData];
    }
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        return self.arr.count;
    } else if (tableView == self.forumTableView) {
        return self.collectionArr.count;
    } else if (tableView == self.CarTableView) {
        return self.carArr.count;
    }
    else {
    return self.TZArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"reuse";
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 80)];
    imageView.image = [UIImage imageNamed:@"cellbg.jpg"];
    if (tableView == self.tableView) {
        CollectTableViewCell *cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:str];
        if (cell == nil) {
            cell = [[CollectTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
        }

        SaveNews *news = [self.arr objectAtIndex:indexPath.row];
        if ([news.image isEqualToString:@"(null)"]) {
            cell.collectImage.image = [UIImage imageNamed:@"zanwu.jpg"];
        } else {
            [cell.collectImage setImageWithURL:[NSURL URLWithString:news.image]];
        }
        self.news = news;
        cell.collectLabel.text = news.title;
        cell.collectLabel.numberOfLines = 0;
        cell.backgroundView = imageView;
 
        return cell;
    } else if (tableView == self.forumTableView) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse1"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
        }
        Base *base = self.collectionArr[indexPath.row];
        cell.textLabel.text = base.name;
        cell.backgroundView = imageView;

        return cell;
    } else if (tableView == self.TZTableView) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse2"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse2"];
        }

        SaveNews *news = [self.TZArr objectAtIndex:indexPath.row];
        self.news = news;
        cell.textLabel.text = news.title;
        cell.textLabel.numberOfLines = 0;
        cell.backgroundView = imageView;
        return cell;
    } else {
         CollectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse3"];
        if (cell == nil) {
            cell = [[CollectTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse3"];
        }
        SaveNews *car = [self.carArr objectAtIndex:indexPath.row];
        self.news = car;
        cell.collectLabel.text = car.title;
        [cell.collectImage setImageWithURL:[NSURL URLWithString:car.image]];
        cell.backgroundView = imageView;
        return cell;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        SaveNews *news = [self.arr objectAtIndex:indexPath.row];
        WebViewController *webVC = [[WebViewController alloc] init];
        webVC.news = news;
        [self.navigationController pushViewController:webVC animated:YES];
    } else if (tableView == self.TZTableView) {
        SaveNews *news = [self.TZArr objectAtIndex:indexPath.row];
        Forum *forum = [[Forum alloc]init];
        forum.topicId = news.url;
        WebController *webVC = [[WebController alloc] init];
        webVC.forum = forum;
        [self.navigationController pushViewController:webVC animated:YES];
    } else if (tableView == self.CarTableView) {
        SaveNews *car = [self.carArr objectAtIndex:indexPath.row];
        HttpViewController *httpVC = [[HttpViewController alloc] init];
        httpVC.news = car;
        [self.navigationController pushViewController:httpVC animated:YES];
    } else if(tableView == self.forumTableView) {
        Base *base = self.collectionArr[indexPath.row];
        ForumDetailController *forumDetailVC = [[ForumDetailController alloc]init];
        forumDetailVC.base = base;
        [self.navigationController pushViewController:forumDetailVC animated:YES];
        [forumDetailVC release];
        
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:animated];
    [self.TZTableView setEditing:editing animated:animated];
    [self.CarTableView setEditing:editing animated:animated];
    
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            [self.arr removeObjectAtIndex:indexPath.row];
            [self.handler deleteNews:self.news];
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
        }
    } else if (tableView == self.TZTableView) {
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            [self.TZArr removeObjectAtIndex:indexPath.row];
            [self.handler deleteForum:self.news];
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
        }
    } else if (tableView == self.CarTableView) {
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            [self.carArr removeObjectAtIndex:indexPath.row];
            [self.handler deleteCar:self.news];
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
        }
    } else if (tableView == self.forumTableView) {
        [self.collectionArr removeObjectAtIndex:indexPath.row];
        Base *base = self.collectionArr[indexPath.row];
        [self.handler deleteCollection:base];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
        
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    DataBaseHandler *handler = [DataBaseHandler shareInstance];
    self.arr = [handler selectAll];
    
    // 给找车数组赋值
    self.carArr = [handler selectAllCar];
    
    // 给帖子数组赋值
    self.TZArr = [handler selectAllForum];
    self.collectionArr = [handler selectCollectionAll];
    
    if (self.arr.count == 0) {
      
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(80, self.view.frame.size.height - 49 - 60, 160, 50)];
        label.textAlignment = 1;
        label.text = @"暂无数据";
        label.tag = 1100;
        label.font = [UIFont systemFontOfSize:20];
        label.backgroundColor = [UIColor whiteColor];
        [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(labelCancel) userInfo:nil repeats:YES];
        [self.view addSubview:label];
       
    
       
    }
    [self.tableView reloadData];
    [self.forumTableView reloadData];
    [self.TZTableView reloadData];
    [self.CarTableView reloadData];
}

- (void)labelCancel
{
    UILabel *label = (UILabel *)[self.view viewWithTag:1100];
    [label removeFromSuperview];
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
